/*
 * 
 * v1.2 by tonydon
 */
package txdnet.util.coder;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import txdnet.util.Logger;
import txdnet.util.StaticMark;

/**
 *
 * @author txdnet
 */
public class AES {

    private AES() {
    }
    private final static String AES = "AES";

    private static byte[] encrypt(byte[] src, byte[] key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            kgen.init(128, new SecureRandom(key));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            return cipher.doFinal(src);
        } catch (Exception e) {
            Logger.error(AES.class, e.toString());
            return null;
        }
    }

    private static byte[] decrypt(byte[] src, byte[] key) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance(AES);
            kgen.init(128, new SecureRandom(key));
            SecretKey secretKey = kgen.generateKey();
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), AES);
            Cipher cipher = Cipher.getInstance(AES);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            return cipher.doFinal(src);
        } catch (Exception e) {
            Logger.error(AES.class, e.toString());
            return null;
        }
    }

    public static String decrypt(String data, String key) throws Exception {
        if (data == null) {
            return data;
        }
        byte[] b = decrypt(ByteHexUtil.hex2byte(data.getBytes(StaticMark.ENCODING_UTF8)), key.getBytes());
        if (b == null) {
            return null;
        } else {
            return new String(b, StaticMark.ENCODING_UTF8);
        }
    }

    public static String encrypt(String data, String key) {
        if (data != null) {
            try {
                return ByteHexUtil.byte2hex(encrypt(data.getBytes(StaticMark.ENCODING_UTF8), key.getBytes()));
            } catch (Exception e) {
                Logger.error(AES.class, e.toString());
            }
        }
        return null;
    }
}
